//
//  UrlRequestManager.m
//  ImitateZH
//
//  Created by lanou3g on 16/3/3.
//  Copyright © 2016年 Highyoung. All rights reserved.
//

#import "UrlRequestManager.h"

@implementation UrlRequestManager
//single_implementation(UrlRequestManager)

/// 请求方法
+(void)requestWith:(requestUrlType)Type URL:(NSString *)url condition:(NSDictionary *)condition SuccessBlock:(successBlock)successBlock failBlock:(failBlock)failBlock{
    if (Type == GET) {
        UrlRequestManager *manager = [[UrlRequestManager alloc] init];
        [manager get:url condition:condition success:successBlock fail:failBlock];
    }else{
        UrlRequestManager *manager = [[UrlRequestManager alloc] init];
        [manager post:url condition:condition success:successBlock fail:failBlock];
    }
}
-(void)get:(NSString *)url condition:(NSDictionary *)condition success:(successBlock)successBlock fail:(failBlock)failBlock{
   
   // 拼接URL
    __block NSMutableString *urlStr = [NSMutableString stringWithString:url];
    // 拼接
    [urlStr appendString:@"?"];
    // 编历添加字典中
    [condition enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [urlStr appendString:[NSString stringWithFormat:@"%@=%@&",key,obj]];
    }];
    // 去掉最后的&符号
    [urlStr substringToIndex:[urlStr length] - 2];
    // 转码url 中有汉字的 要转
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:urlStr];
    NSString *URLfinally = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:set];
    
    // 设置request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLfinally]];
    [request setHTTPMethod:@"GET"];
       NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        id item = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
        if (successBlock) {  //如果解析成功
            successBlock(item);
            return ;
        }else{
            NSLog(@"successblock  empty");
            return;
        }
    }];
    
    [task resume];
 
    
}
-(void)post:(NSString *)url condition:(NSDictionary *)condition success:(successBlock)successBlock fail:(failBlock)failBlock{
    NSURLSession *session = [NSURLSession sharedSession];
    // 拼接url
    NSMutableString *urlStr = [NSMutableString stringWithString:url];
    // 拼接?
    [urlStr appendString:@"?"];
    
    // 转码
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:urlStr];
    NSString * urlString = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:set];

    // body
    __block NSMutableString *bodyStr = [NSMutableString string ];
    [condition enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [bodyStr appendString:[NSString stringWithFormat:@"%@=%@&",key,obj]];
    }];
    [bodyStr substringToIndex:[bodyStr length] - 2];
   
    // 设置request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    // 设置请求方式
    [request setHTTPMethod:@"POST"];
    // 设置body
    NSData *date = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:date];
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //NSLog(@"data = %@, err = %@",data,error);
        if (data && !error) {
            id item = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
            if (successBlock) {  //如果解析成功
                successBlock(item);
                return ;
            }else {
                NSLog(@"successblock 为空");
                return;
            }
        }
        //
        if (failBlock) {
            failBlock(error);
        }
    }];
    [task resume];

}



@end
